import 'dart:async';

import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_page.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/bean/version_entity.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/views/home/model/order_manager_model.dart';
import 'package:yuan_hang_app/views/home/view/order/order_detail_page.dart';
import 'package:yuan_hang_app/views/home/view/order/order_edit_page.dart';
import 'package:yuan_hang_app/views/home/view/store/store_detail_page.dart';
import 'package:yuan_hang_app/widget/common_dialog.dart';

import 'package:yuan_hang_app/widget/custom_search.dart';
import 'package:yuan_hang_app/widget/custom_tab.dart';
import 'package:yuan_hang_app/widget/sort_content.dart';
import 'package:yuan_hang_app/widget/status_btn.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_list_view.dart';
import 'package:yuan_hang_app/widget/w_popup_window.dart';
import 'package:yuan_hang_app/widget/w_text.dart';

///下单管理
class StoreManagerPage extends StatefulWidget {
  const StoreManagerPage({super.key});

  @override
  BaseState<StoreManagerPage> createState() => _StoreManagerPageState();
}

class _StoreManagerPageState extends BaseState<StoreManagerPage> {
  List<Map> modelList =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.carType);
  List<Map> versionList = [];
  List currentOrderList = [];

  WListViewState? listState;

  String modelId = "";
  Map sortParams = {};

  Map<String, dynamic> queryParams = {"pageNum": 1, "limit": 20};

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
      title: "车辆库存",
      child: Column(
        children: [
          CustomSearch(
            hintText: "订单编号",
            //    showSort: false,
            onTextChange: (text) {
              queryParams["orderNo"] = text;
              queryParams["pageNum"] = 1;
              showLoading();
              CommonUtils.antiShake(getOrderList);
            },
            onSortClick: () {
              WPopupWindow.showSort(
                  context: context,
                  sortType: SortType.CAR_STORE,
                  sortParams: sortParams,
                  isScrollControlled: true,
                  onSelected: (params) {
                    sortParams = params;
                    print("params$params");
                    params.forEach((key, value) {
                      queryParams[key] = value;
                      if (queryParams.containsKey(key) && value == null) {
                        queryParams.remove(key);
                      }
                    });
                    showLoading();
                    getOrderList();
                  });
            },
          ),
          Expanded(
              child: WListView(
            itemBuilder: _orderItem,
            padding: EdgeInsets.symmetric(vertical: 10.px),
            getDataList: (currentState, page) {
              listState = currentState;
              queryParams["pageNum"] = page;
              getOrderList();
            },
          )),
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
  }

  void getOrderList() {
    HttpUtils().get(Api.getStoreList, queryParams: queryParams).then((data) {
      hideLoading();
      if (data.resultCode == 200) {
        listState?.onRefreshData(
            data.data["records"] ?? [], queryParams["pageNum"]);
      } else if (data.resultCode == 500) {
        listState?.onFail(data.errMsg);
      }
    }).catchError((e) {
      hideLoading();
    });
  }

  Widget _orderItem(context, index, list) {
    Map item = list[index];
    Map matchStatus =
        orderManagerModel.exchangeMatchStatus(item["vhclMatchStatus"]);
    return GestureDetector(
      onTap: () {
        RouteHelper.pushWidget(
            context,
            StoreDetailPage(
              storeInfo: item,
            ));
      },
      child: Container(
        margin: EdgeInsets.only(left: 15.px, right: 15.px, bottom: 10.px),
        padding: EdgeInsets.only(top: 10.px, right: 10.px, bottom: 5.px),
        decoration: BoxDecoration(
            color: WColors.white, borderRadius: BorderRadius.circular(10.px)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                WLine(
                  marginRight: 10.px,
                  height: 16.px,
                  width: 4.px,
                  color: WColors.primaryColor,
                ),
                Expanded(
                  child: Row(
                    children: [
                      WText(
                        StringUtils.safeGetValue(item["orderNo"]),
                        style: TextStyle(
                            color: WColors.mainTextColor,
                            fontSize: WDimens.tsLarge,
                            fontWeight: FontWeight.bold),
                      ),
                      SizedBox(
                        width: 10.px,
                      ),
                      StatusBtn(
                        text: CommonReqUtils.exchangeCodeToName2(
                                WConstant.storeCarStatusList,
                                item["lifeCycle"]) ??
                            "",
                        color: WColors.border,
                        isItemBtn: true,
                        height: 28.px,
                        // width: 32.px,
                        fontColor: WColors.hintTextColor,
                      )
                    ],
                  ),
                ),
                StatusBtn(
                  text: matchStatus["title"],
                  color: matchStatus["color"],
                  isItemBtn: true,
                  isTag: true,
                  height: 28.px,
                  width: 60.px,
                  onPressed: () {},
                )
              ],
            ),
            WLine(
              height: 0.5.px,
              marginTop: 5.px,
              marginBottom: 5.px,
              marginLeft: 10.px,
            ),
            Padding(
              padding: EdgeInsets.only(left: 10.px),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  WText(
                      "${StringUtils.safeGetValue(item["modelName"])} · "
                      "${StringUtils.safeGetValue(item["configName"])} · "
                      "${StringUtils.safeGetValue(item["colorName"])} · "
                      "${StringUtils.safeGetValue(item["trimColorName"])} ",
                      style: TextStyle(
                          color: WColors.subTextColor,
                          fontSize: WDimens.tsMedium)),
                  SizedBox(
                    height: 5.px,
                  ),
                  WText(
                      "${CommonReqUtils.exchangeCodeToName2(WConstant.storeOrderStatusList, item["orderType"])}   ${StringUtils.safeGetValue(item["sname"])} ",
                      style: TextStyle(
                          color: WColors.subTextColor,
                          fontSize: WDimens.tsMedium)),
                  SizedBox(
                    height: 5.px,
                  ),
                  WText(
                      "仓库名称： ${StringUtils.safeGetValue(item["warehouseName"])} ",
                      style: TextStyle(
                          color: WColors.subTextColor,
                          fontSize: WDimens.tsMedium)),
                  SizedBox(
                    height: 5.px,
                  ),
                  WText(
                    "入库日期：${StringUtils.safeGetValue(item["storageDate"])}",
                    textAlign: TextAlign.right,
                    style: TextStyle(
                      color: WColors.hintTextColor,
                      fontSize: WDimens.tsMedium,
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
